package com.itany.springboot.typehandler;

import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.springframework.util.StringUtils;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class StringArrayTypeHandler extends BaseTypeHandler<String[]> {

    public static final String SPLIT=",";

    @Override
    public void setNonNullParameter(PreparedStatement preparedStatement, int i, String[] strings, JdbcType jdbcType) throws SQLException {
        if(strings!=null){
            preparedStatement.setString(i, StringUtils.arrayToDelimitedString(strings,SPLIT));
        }
    }

    @Override
    public String[] getNullableResult(ResultSet resultSet, String columnName) throws SQLException {
        if(resultSet.getString(columnName)!=null){
            return resultSet.getString(columnName).split(SPLIT);
        }
        return null;
    }

    @Override
    public String[] getNullableResult(ResultSet resultSet, int columnIndex) throws SQLException {
        if(resultSet.getString(columnIndex)!=null){
            return resultSet.getString(columnIndex).split(SPLIT);
        }
        return null;
    }

    @Override
    public String[] getNullableResult(CallableStatement callableStatement, int columnIndex) throws SQLException {
        if(callableStatement.getString(columnIndex)!=null){
            return callableStatement.getString(columnIndex).split(SPLIT);
        }
        return null;
    }
}
